package com.cqie.practicaltraining.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.practicaltraining.config.result.R;
import com.cqie.practicaltraining.domain.Datas;
import com.cqie.practicaltraining.domain.Pasture;
import com.cqie.practicaltraining.dto.DataSelectDto;
import com.cqie.practicaltraining.dto.PageResult;
import com.cqie.practicaltraining.service.DatasService;
import com.cqie.practicaltraining.mapper.DatasMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 9977
 * @description 针对表【datas(字典数据)】的数据库操作Service实现
 * @createDate 2024-12-26 10:47:28
 */
@Service
public class DatasServiceImpl extends ServiceImpl<DatasMapper, Datas> implements DatasService {
    @Autowired
    private PastureServiceImpl pastureService;

    @Override
    public R searchDataByCondition(DataSelectDto dataSelectDto) {
        LambdaQueryWrapper<Datas> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(dataSelectDto.getDataName() != null, Datas::getDataName, dataSelectDto.getDataName())
                .like(dataSelectDto.getStatus() != null, Datas::getStatus, dataSelectDto.getStatus())
                .eq(dataSelectDto.getTypeId() != null, Datas::getTypeId, dataSelectDto.getTypeId());
        IPage<Datas> page = new Page<>(dataSelectDto.getPageNumber(), dataSelectDto.getPageSize());
        IPage<Datas> resultPage = page(page, wrapper);
        PageResult<Datas> result = new PageResult<>(resultPage.getRecords(), dataSelectDto.getPageNumber(), dataSelectDto.getPageSize(), resultPage.getTotal());
        if (!result.getRecords().isEmpty())
            return R.Success("查询成功", result);
        return R.Failed("暂无数据");
    }

    @Override
    public R saveData(String dataName, Long typeId) {
        if (dataName == null || typeId == null)
            return R.Failed("数据名或数据类型不能为空");
        // 验证数据名是否只包含中文字符
        if (!dataName.matches("[\\u4e00-\\u9fa5]+")) {
            return R.Failed("数据名只能包含中文字符，不能有特殊符号");
        }
        LambdaQueryWrapper<Datas> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Datas::getDataName, dataName).eq(Datas::getTypeId, typeId);
        Datas existingData = getOne(wrapper);
        if (existingData != null) {
            if (existingData.getStatus() == 1)
                return R.Failed("该数据已存在");
            else {
                return R.Failed("该数据被停用，请启用");
            }
        }
        Datas datas = new Datas();
        datas.setDataName(dataName.trim());
        datas.setTypeId(typeId);
        datas.setCreateTime(new Date());
        if (save(datas))
            return R.Success("添加成功");
        return R.Failed("添加失败");
    }

    @Override
    public R updateDataStatus(Long dataId) {
        if (dataId == null) {
            return R.Failed("数据ID不能为空");
        }
        LambdaQueryWrapper<Datas> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Datas::getDataId, dataId);
        Datas datas = getOne(wrapper);
        if (datas == null) {
            return R.Failed("该数据不存在");
        }
        LambdaQueryWrapper<Pasture> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Pasture::getBreedsLivestock, datas.getDataName());
        List<Pasture> pastureList = pastureService.list(wrapper1);
        List<String> pastureNames = new ArrayList<>();
        int count = 0;
        for (Pasture pasture : pastureList) {
            if (pasture.getStatus() == 1) {
                count++;
                pastureNames.add(pasture.getPastureName());
            }
        }
        if (count > 0) {
            String pastureNamesString = String.join(", ", pastureNames);
            return R.Failed("该数据已被 " + count + " 个 " + pastureNamesString + " 使用，无法改变状态");
        }
        Datas datas1 = new Datas();
        if (datas.getStatus() == 1)
            datas1.setStatus(0);
        else
            datas1.setStatus(1);
        datas1.setDataId(dataId);
        datas1.setUpdatedTime(new Date());
        try {
            if (updateById(datas1)) {
                return R.Success("状态已改变");
            } else {
                return R.Failed("状态未改变");
            }
        } catch (Exception e) {
            log.error("更新数据状态时发生异常", e);
            return R.Failed("更新数据状态时发生异常");
        }
    }

    @Override
    public R getAllData() {
        LambdaQueryWrapper<Datas> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Datas::getStatus, 1);
        if (list(wrapper) != null)
            return R.Success("查询成功", list(wrapper));
        return R.Failed("暂无数据");
    }

}




